<template>
  <!-- 添加小类 -->
  <SmallAutocomplete ref="select_small_list_test" @return_small="update_small_row"/>
  <HandleAutocomplete ref="select_handle_list_test" @return_small="update_handle_row"/>

  <!-- 增加和筛选零件种类 表头部分-->
  <el-card style="background-color: white">
    <el-form ref="record_query_form" :label-position=" 'right' " :inline="true">

      <!-- 将以下所有记录都视为出库/入库 -->
      <el-form-item label="出入库方向">
        <el-radio-group
            v-model="all_record_trend"
        >
          <el-radio-button :label="false">入库</el-radio-button>
          <el-radio-button :label="true">出库</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="处理方检索方式">
        <el-radio-group
            v-model="handle_select_method"
        >
          <el-radio-button :label=" '名称' ">名称</el-radio-button>
          <el-radio-button :label=" '助记码' ">助记码</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <!-- 为所有记录选择日期 -->
      <el-form-item label="自动日期时间">
        <el-date-picker
            v-model="all_record_date"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            @blur="make_hms"
        />
      </el-form-item>

      <el-form-item label="小时修正">
        <el-input-number v-model="time_change" :min="-23" :max="23" :precision="0" :step="1"/>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" @click="SubmitRecord()">提交</el-button>
      </el-form-item>

      <el-form-item>
        <el-button @click=" DeleteAllRecord() ">清空全部记录</el-button>
        <el-button @click=" DeleteAllRecord() ">清空全部记录</el-button>
        <el-button @click=" row_increase() ">增加一条记录</el-button>
        <el-button @click=" select_small_table_col() ">选择表头</el-button>
        <el-button type="primary" @click="total_total()">页面合计</el-button>
        {{ total_cmy }}元
      </el-form-item>

    </el-form>
  </el-card>

  <!-- 表格部分 -->
  <el-table
      :data="in_out_order"
      highlight-current-row
  >
    <el-table-column type="index" width="50px"/>

    <el-table-column width="60px">
      <template #default="scope">
        <el-button type="primary" circle @click="small_no_clear_all(scope.$index)">
          <el-icon>
            <Delete/>
          </el-icon>
        </el-button>
      </template>
    </el-table-column>

    <el-table-column label="日期" prop="actual_date" v-if=" table_col_visible.actual_date "/>
    <el-table-column label="大类名称" prop="big_name" v-if=" table_col_visible.big_name "/>

    <el-table-column label="编号 | 名称 | 型号" prop="small_name" width="500px">

      <template #default="scope: {row: InOut2}">
        <div >
        <el-input
            class="input-with-select_InOut2"
            v-model="scope.row.small_name"
            @keyup.enter="autocomplete_small_info(scope.row)"
            @blur="blur_input(scope.row)"
            @focus="focus_input(scope.row)"
        >
          <template #prepend>
            <el-input
                v-model="scope.row.no"
                @keyup.enter="autocomplete_small_info(scope.row)"
                @blur="blur_input(scope.row)"
                @focus="focus_input(scope.row)"
            />
          </template>
          <template #append>
            <el-input
                v-model="scope.row.model"
                @keyup.enter="autocomplete_small_info(scope.row)"
                @blur="blur_input(scope.row)"
                @focus="focus_input(scope.row)"
            />
          </template>
        </el-input>
        </div>
      </template>
    </el-table-column>


    <el-table-column label="单位" prop="units"/>

    <el-table-column label="处理方" prop="handle_name" width="250px">
      <template #default="scope: {row: InOut2; $index:number}">

        <el-input
            class="input-with-select_InOut2"
            v-model="scope.row.handle_name"
            @keyup.enter="components_querySearchHandleMnemonic(scope.row)"
            @blur="check_input_handle_name(scope.row)"
        >

          <template #prepend>
            <el-button @click="handle_mnemonic_copy(scope.$index, scope.row)" style="width: 80px">
              <el-icon>
                <Pointer/>
              </el-icon>
            </el-button>
          </template>

          <template #append>
            <el-button @click="handle_mnemonic_clear_all(scope.row)" style="width: 80px">
              <el-icon>
                <Delete/>
              </el-icon>
            </el-button>
          </template>

        </el-input>

      </template>
    </el-table-column>

    <el-table-column label="数量" width="180px">
      <template #default="scope: {row: InOut2}">
        <el-input v-model="scope.row.change" @change="unit_price_change($event, scope.row)"/>
      </template>
    </el-table-column>

    <el-table-column label="现有数量" prop="number" width="100px"/>

    <el-table-column label="单价" width="180px">
      <template #default="scope: {row: InOut2}">
        <el-input v-model="scope.row.unit_price"
                  @change="unit_price_total($event,scope.row)"/>
      </template>
    </el-table-column>

    <el-table-column label="合计">
      <template #default="scope: {row: InOut2}">
        <el-input v-model="scope.row.total"
                  @change="local_total($event,scope.row)"/>
      </template>
    </el-table-column>

    <el-table-column label="备注" v-if=" table_col_visible.remarks ">
      <template #default="scope: {row: InOut2}">
        <el-input v-model="scope.row.remarks"/>
      </template>
    </el-table-column>

    <el-table-column label="结果" width="60px">
      <template #default="scope: {row: InOut2}">
        <el-tooltip
            class="box-item"
            effect="dark"
            :content="scope.row.content_value"
            placement="left"
        >
          <el-button :type="scope.row.type_value" size="small"></el-button>
        </el-tooltip>
      </template>
    </el-table-column>

  </el-table>


  <!-- 选择显示表格的列 -->
  <el-dialog
      v-model="small_table_head_show_visible"
      title="表头选项"
      :close-on-click-modal='false'
      :close-on-press-escape='false'
      :show-close='false'
  >
    <el-checkbox v-model="table_col_visible.actual_date" label="日期时间"/>
    <el-checkbox v-model="table_col_visible.remarks" label="备注"/>
    <el-checkbox v-model="table_col_visible.big_name" label="大类名称"/>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="select_small_table_col_confirm()">确定</el-button>
      </span>
    </template>
  </el-dialog>


</template>
<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import {useStore} from "@/pinia"
import {InOut2, record_list, RecordTableCRUDResponseData} from "@/api/first/PartsManagement/type.ts";
import {reqRecordList} from "@/api/first/PartsManagement";
import {ElMessage, ElMessageBox} from "element-plus";
import {Delete, Pointer} from "@element-plus/icons-vue";
import {reqHandleFuzzySearch, reqSmallFuzzySearchM} from "@/api/first/FuzzySearch";
import {
  HandleFuzzyList,
  HandleFuzzySearchResponse,
  SmallFuzzyList,
  SmallFuzzySearchResponse
} from "@/api/first/FuzzySearch/type.ts";
import SmallAutocomplete from "@/page/first/InboundOutbound1/SmallAutocomplete.vue";
import HandleAutocomplete from "@/page/first/InboundOutbound1/HandleAutocomplete.vue";

// 小时数自动修正
const time_change = ref(0)



// 在末尾增加一行
const row_increase = () => {
  in_out_order.value.push({
    big_id: '',
    small_id: '',
    handle_id: '',
    index: make_index(),

    big_name: '',
    small_name: '',
    no: '',
    actual_date: null,
    handle_name: '',

    change: '',
    unit_price: '',
    total: '',

    trend: '',
    remarks: '',
    units: '',
    model: '',
    number: '/',

    content_value: '尚未提交',
    type_value: '',

    small_no_temp: '',
    handle_name_temp: '',
    small_name_temp: '',
    model_temp: ''
  })
}




const update_small_row = (row: SmallFuzzyList) => {
  selected_line_row_save.small_name = row.small_name
  selected_line_row_save.small_name_temp = row.small_name
  selected_line_row_save.small_no_temp = row.no
  selected_line_row_save.no = row.no
  selected_line_row_save.model = row.model
  selected_line_row_save.model_temp = row.model

  selected_line_row_save.small_id = row.small_id
  selected_line_row_save.unit_price = String(row.unit_price)
  selected_line_row_save.units = row.units
  selected_line_row_save.big_name = row.big_name
  selected_line_row_save.big_id = row.big_id
  selected_line_row_save.number = row.number
}

// 打开时间选择器后，设置时间为当前时间
const make_hms = () => {

  let temp10 = all_record_date.value

  if(temp10 !== '' && temp10 !== null && temp10 !== undefined){

    let YMD = temp10.slice(0, 11)
    let h = temp10.slice(11, 13)
    let ms = temp10.slice(13, 19)

    let temp: number = parseInt(h)
    if(temp + time_change.value < 0){
      temp = 0
    }else if(temp + time_change.value > 23){
      temp = 23
    }else{
      temp = temp + time_change.value
    }

    h = (temp < 10 ? '0' + temp : temp);

    all_record_date.value = YMD + h + ms
    console.log('all_record_date.value', all_record_date.value)

  }
}
const store = useStore()

// 如果输入数量不正确则一直为空
const unit_price_change = (value: string, row: InOut2) => {
  if (regex_match.test(value)) {

    if (row.unit_price !== '') {
      row.total = String(parseFloat((parseFloat(row.unit_price) * parseFloat(value)).toFixed(4)))
    } else if (row.total !== '') {
      row.unit_price = String(parseFloat((parseFloat(row.total) / parseFloat(value)).toFixed(4)))
    } else {
    }

  } else {
    row.change = ''
  }
}

const unit_price_total = (value: string, row: InOut2) => {
  if (regex_match.test(value)) {
    if (row.change !== '') {
      row.total = String(parseFloat((parseFloat(row.change) * parseFloat(value)).toFixed(4)))
    }
  } else {
    row.change = ''
  }
}

const local_total = (value: string, row: InOut2) => {
  if (regex_match.test(value)) {
    if (row.change !== '') {
      row.unit_price = String(parseFloat((parseFloat(value) / parseFloat(row.change)).toFixed(4)))
    }
  } else {
    row.change = ''
  }
}


// 面板部分，选择日期时间和出入库方向
// -------------------------------------------------------------
const all_record_date = ref<string>('')  // 日期时间
const all_record_trend = ref<boolean>(false)  // 出入库方向
const handle_select_method = ref<'名称' | '助记码'>('名称')
const in_out_order = ref<InOut2[]>([])  // 填写表格的数据ref

const table_col_visible = reactive({  // 选择显示的列
  remarks: false,
  actual_date: false,
  big_name: false,
})
const small_table_head_show_visible = ref<boolean>() // 决定选择列的框是否显示
// 选择表格可以导出的列
const select_small_table_col = () => {
  small_table_head_show_visible.value = true
}
const select_small_table_col_confirm = () => {
  small_table_head_show_visible.value = false
}
const total_cmy = ref('')
const total_total = () => {
  let total = 0.0
  for (let i of in_out_order.value) {
    if (i.total !== '') {
      total += parseFloat(i.total)
    }
  }
  total_cmy.value = String(total.toFixed(2))
}

// 小类编号，名称和型号的模糊搜索
//-------------------------------------------
const test2 = ref(-1)
const test4= ref()
const blur_input = (row: InOut2) => {
  if(test2.value != row.index){
    test2.value = row.index
    test4.value = row
  }
}
const focus_input = (row: InOut2) => {
  if(test2.value != row.index){
    test4.value.small_name = test4.value.small_name_temp
    test4.value.no = test4.value.small_no_temp
    test4.value.model = test4.value.model_temp
  }
}

const select_small_list_test = ref()

let selected_line_row_save: InOut2

const autocomplete_small_info = (row: InOut2) => {

  if (row.no === '' && row.small_name === '' && row.model === '') {
    ElMessage.warning('在编号，小类名称，型号中至少输入一个筛选条件')
  } else {
    reqSmallFuzzySearchM({
      small_name: row.small_name,
      no: row.no,
      model: row.model
    }).then((result: SmallFuzzySearchResponse) => {
      select_small_list_test.value?.open(result.small_fuzzy_list as SmallFuzzyList[])
      selected_line_row_save = row
    })
  }
}

// 删除表格中的一行
const small_no_clear_all = (index: number) => {
  in_out_order.value.splice(index, 1)
}

// 处理方模糊搜索
//-------------------------------------------
const select_handle_list_test = ref()

const update_handle_row = (row: HandleFuzzyList) => {
  selected_line_row_save.handle_name = row.handle_name
  selected_line_row_save.handle_name_temp = row.handle_name
  selected_line_row_save.handle_id = row.handle_id
}

const check_input_handle_name = (row: InOut2) => {
  if (row.handle_name !== row.handle_name_temp) {
    row.handle_name = row.handle_name_temp
  }
}

const components_querySearchHandleMnemonic = (row: InOut2) => {
  if (row.handle_name !== row.handle_name_temp) {
    // 执行查询操作
    reqHandleFuzzySearch({
      mode: handle_select_method.value,
      fuzzy_search_object: row.handle_name
    }).then((result: HandleFuzzySearchResponse) => {
      // 弹出选择框
      select_handle_list_test.value?.open(result.handle_fuzzy_list as HandleFuzzyList[])
      selected_line_row_save = row
    })
  }
}

// 复制上一行处理方的信息到下一行
const handle_mnemonic_copy = (index: number, row: InOut2) => {
  if(index !== 0){
    row.handle_name = row.handle_name_temp = in_out_order.value[index-1].handle_name
    row.handle_id = in_out_order.value[index-1].handle_id
  }
}

// 删除处理方输入框中的内容
const handle_mnemonic_clear_all = (row: InOut2) => {
  row.handle_name = ''
  row.handle_id = ''
  row.handle_name_temp = ''
}


// 执行检查，并在确认无误后添加所有记录
// ------------------------------------------------
const regex_match = /^([1-9]\d{0,9}|0)(\.\d{1,4})?$/  // 对金额进行正则检查

const SubmitRecord = async () => {
  console.log('store.axios_path', store.axios_path)

  let temp10
  if (all_record_trend.value === false) {
    temp10 = '入库'
  } else {
    temp10 = '出库'
  }
  // 二次确认
  await ElMessageBox.confirm(
      `确认您选择的方向是${temp10}，时间日期为${all_record_date.value}`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )

  // 检查并赋予全部记录时间
  if (all_record_date.value === '') {
    ElMessage.warning('尚未选择日期时间')
    return
  }
  let temp1 = new Date(all_record_date.value);
  let temp2
  for (let i of in_out_order.value) {
    temp2 = new Date(temp1.setSeconds(temp1.getSeconds() + 5));
    temp1 = temp2

    const year = temp2.getFullYear();
    const month = ('0' + (temp2.getMonth() + 1)).slice(-2);
    const day = ('0' + temp2.getDate()).slice(-2);
    const hour = ('0' + temp2.getHours()).slice(-2);
    const minute = ('0' + temp2.getMinutes()).slice(-2);
    const second = ('0' + temp2.getSeconds()).slice(-2);

    i.actual_date = `${year}-${month}-${day} ${hour}:${minute}:${second}`
  }

  // 赋予全部记录出入库方向
  for (let i of in_out_order.value) {
    i.trend = all_record_trend.value
  }

  let add_list: record_list[] = []

  //decimal(11,2) 的正则表达式检查

  let table_error = false


  for (let item of in_out_order.value) {
    // 如果列表中已经有了成功的记录，再次提交的时候直接略过
    if (item.type_value === 'primary') {
      continue
    }

    if (item.type_value === 'success') {
      item.type_value = 'primary'
      item.content_value = '在本轮提交前已经成功提交，请删除本条记录'
      continue
    }

    //如果这行记录什么都没填写，直接跳过就行
    if (item.handle_id === '' || item.small_id === '') {
      continue
    }

    let temp = <{
      actual_date: string,
      handle: number | string,
      change: null | string,
      unit_price: null | string,
      trend: boolean | string,
      remarks: string,
      small: number | string,
      index: number | string,
      operator: string
    }>{
      actual_date: '',
      handle: '',
      change: null,
      unit_price: null,
      trend: '',
      remarks: '',
      small: '',
      index: '',
      operator: ''
    }

    temp.actual_date = item.actual_date as string
    temp.trend = item.trend

    // 检测是否存在handle_id
    if (item.handle_id === '') {
      item.type_value = 'info'
      item.content_value = '没有选择供应商'
      table_error = true
      continue
    } else {
      temp.handle = item.handle_id as number
    }

    // 数量，单价，合计综合检测

    // 检测是否存在change，以及是否为（9.2）
    if (Number(item.change) === 0) {
      item.type_value = 'info'
      item.content_value = '没有输入数量或数量为0'
      table_error = true
      continue
    } else {
      if (regex_match.test(item.change)) {
        temp.change = item.change
      } else {
        item.type_value = 'info'
        item.content_value = '数量输入非法'
        table_error = true
      }
    }
    // 检测是否存在单价，以及是否为（9.2）
    if (Number(item.change) === 0) {
      item.type_value = 'info'
      item.content_value = '没有输入数量或数量为0'
      table_error = true
      continue
    } else {
      if (regex_match.test(item.unit_price as string)) {
        temp.unit_price = item.unit_price
      } else {
        item.type_value = 'info'
        item.content_value = '单价输入非法'
        table_error = true
      }
    }

    // 检测是否存在合计，仅仅在数量，合计存在而单价不存在的时候才进行检测

    if (Number(item.total) === 0) {
      item.type_value = 'info'
      item.content_value = '没有输入数量或数量为0'
      table_error = true
      continue
    } else {
      if (regex_match.test(item.total as string)) {
        temp.unit_price = item.unit_price
      } else {
        item.type_value = 'info'
        item.content_value = '单价输入非法'
        table_error = true
      }
    }

    // remarks 只保留前20个字符
    if (item.remarks.length > 20) {
      item.type_value = 'info'
      item.content_value = '备注长度超过20个字符'
      table_error = true
      continue
    } else {
      temp.remarks = item.remarks
    }

    //small_id
    if (item.small_id === '') {
      item.type_value = 'info'
      item.content_value = '未选择小类'
      table_error = true
      continue
    } else {
      temp.small = item.small_id
    }

    if (table_error) {
      continue
    }

    // index
    temp.index = item.index
    // operator
    temp.operator = store.username
    // 添加
    add_list.push(temp)
  }

  if (add_list.length === 0) {
    ElMessage.warning('没有合法的提交记录')
  } else {
    reqRecordList({
      mode: "create",
      create: {
        list: add_list
      },
    }).then((result: RecordTableCRUDResponseData) => {
      if (typeof result.create !== 'undefined') {
        let error_type = false
        for (let i of result.create) {
          for (let j of in_out_order.value) {
            if (j.index === i.index) {
              // 如果返回的是成功
              if (i.success === '') {
                j.type_value = 'success'
                j.content_value = '添加成功'
              } else {
                error_type = true
                j.type_value = 'danger'
                j.content_value = <string>i.error
              }
              break
            }
          }
        }
        if (!error_type) {
          ElMessage.success('全部提交成功')
        } else {
          ElMessage.warning('存在未提交成功的项，请检查')
        }
      }
    })
  }
}


// 清空所有记录
// ------------------------------------------------
const DeleteAllRecord = () => {
  total_cmy.value = ''
  all_record_date.value = ''
  for (let i of in_out_order.value) {
    i.big_id = ''
    i.small_id = ''
    i.handle_id = ''
    i.index = make_index()

    i.big_name = ''
    i.small_name = ''
    i.no = ''
    i.actual_date = null
    i.handle_name = ''

    i.change = ''
    i.unit_price = ''
    i.total = ''

    i.trend = ''
    i.remarks = ''
    i.units = ''
    i.model = ''
    i.number = '/'
    i.content_value = '尚未提交'
    i.type_value = ''

    i.small_no_temp = ''
    i.handle_name_temp = ''
    i.model_temp = ''
    i.small_name_temp = ''
  }
  ElMessage.success('记录清除成功！')
}


// 默认表格行数为40行,进入页面后生成所有行
// ------------------------------------------------
onMounted(() => {
  for (let i = 1; i <= 40; i++) {
    in_out_order.value.push({
      big_id: '',
      small_id: '',
      handle_id: '',
      index: make_index(),

      big_name: '',
      small_name: '',
      no: '',
      actual_date: null,
      handle_name: '',

      change: '',
      unit_price: '',
      total: '',

      trend: '',
      remarks: '',
      units: '',
      model: '',
      number: '/',

      content_value: '尚未提交',
      type_value: '',

      small_no_temp: '',
      handle_name_temp: '',
      small_name_temp: '',
      model_temp: ''
    })
  }
})
// 生成每一行的唯一编号
let table_index = 1
const make_index = () => {
  let temp = table_index
  table_index += 1
  return temp
}


</script>

<style>
.el-table td, el-table th {
  padding: 0
}

.input-with-select_InOut2 .el-input-group__prepend {
  padding: 0;
}

.input-with-select_InOut2 .el-input-group__append {
  padding: 0;
}
</style>
